/**
 * 
 */
package cn.ad.server.web.servlet.v2.requesthandler;

import cn.ad.server.common.utils.BrowserUtils;
import cn.ad.server.common.utils.IPUtils;
import cn.ad.server.web.log.entity.AdTrackingEventLog;
import cn.ad.server.web.servlet.v2.parser.AdRequestParseException;
import cn.ad.server.web.servlet.v2.parser.DefaultImpressionRequestParser;
import cn.ad.server.web.servlet.v2.parser.ParameterParseExcption;
import cn.ad.server.web.servlet.v2.parser.TrackingRequestParser;
import cn.ad.server.web.servlet.v2.requests.TrackingRequest;
import cn.ad.server.web.servlet.v2.requests.TrackingResponse;
import cn.ad.server.web.spring.model.IAdserverRequest;
import cn.ad.server.web.spring.service.actions.context.IPContext;
import cn.ad.server.domain.IPDetail;
import cn.ad.server.domain.enumration.ResponseStatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 广告转发点击请求处理Handler
 * @author dongbin.yu
 */
public class ClickForwardRequestHandler extends TrackingRequestHandler {

	private static Logger LOGGER = LoggerFactory.getLogger(ClickForwardRequestHandler.class);

	/**
	 *
	 */
	public ClickForwardRequestHandler() {
		//设置缺省默认的展示请求解析
		setDefaultParser(new DefaultImpressionRequestParser());
	}

	public void handle(HttpServletRequest request, HttpServletResponse response) throws RequestHandleException {
		TrackingRequest trackingReq = null;
		TrackingResponse trackingRes = null;
		IAdserverRequest adReq = null;
		try {
			String channel = getChannel(request);
			TrackingRequestParser parser = getDefaultParser();

			if (parser == null) {
				throw new RequestHandleException("缺省的监测消息解析实例没有初始化.");
			}
			// 解析请求参数
			adReq = parser.parse(request);
			if (adReq == null) {
				throw new AdRequestParseException("AdRequest is null.");
			}

			if (adReq instanceof TrackingRequest) {
				trackingReq = (TrackingRequest) adReq;
				trackingReq.setChannelID(channel);
				trackingRes = handleTracking(trackingReq);
			} else {
				throw new RequestHandleException(
						"The Request of Tracking is not support. class:" + adReq.getClass().getName());
			}
			handleResponse(response, parser, trackingReq, trackingRes);
		} catch (ParameterParseExcption ex) {
			if (ex.getResult() != null) {
				trackingReq = (TrackingRequest) ex.getResult();
				trackingRes = new TrackingResponse(ResponseStatusCode.INVALID_REQ_PARAMETER.value());
			}
			LOGGER.warn("解析监测接口参数 [{} = {}]出现异常:" + ex.getMessage(), ex.getParamName(), ex.getParamValue(), ex);
		} catch (AdRequestParseException ex) {
			throw new RequestHandleException("请求消息解析出现异常.", ex);
		} catch (Exception e) {
			LOGGER.error("广告监测请求处理异常，系统内部错误:{}", e.getMessage(), e);
		} finally {
			doEventLog((TrackingRequest) adReq);
		}
	}

	private void doEventLog(TrackingRequest request){

		AdTrackingEventLog event = new AdTrackingEventLog();

		event.setRequestTimestamp(request.getRequestTimestamp());
		event.setRequestIp(request.getIp());
		event.setServerId(IPUtils.getHostName());
		event.setPlatformId(request.getPlatform_id());
		event.setAdxType(request.getPlatform_id() == 0 ? AdTrackingEventLog.SYSTEM_PLATFORM_ID : request.getPlatform_id());
		event.setChannel_id(request.getChannelID());

		event.setUa(request.getUa());
		event.setBrowser(BrowserUtils.getBrowser(request.getUa()));

		IPDetail ipDetail = IPContext.instance().getIPDetail(IPUtils.convertIPToLong(request.getIp()));
		if (ipDetail != null) {
			event.setCountryId(ipDetail.getCountryId());
			event.setStateId(ipDetail.getStateId());
			event.setCityId(ipDetail.getCityId());
			event.setAreaId(ipDetail.getDistrictId());
		}

		event.setEventType(AdTrackingEventLog.FORWARD_CLICK);
		event.setAdspaceId(request.getAid());
		event.setGuid(request.getGuid());
		logAdserverEventLog(event);
	}

}
